package com.yserp.project.erp.order.productorder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yserp.common.exception.BusinessException;
import com.yserp.common.utils.StringUtils;
import com.yserp.common.utils.bean.BeanUtils;
import com.yserp.common.utils.mybatis.MybatisPlusUtil;
import com.yserp.common.utils.text.Convert;
import com.yserp.project.erp.common.enums.CheckStatusEnums;
import com.yserp.project.erp.common.enums.OrderEnums;
import com.yserp.project.erp.order.productbom.domain.ProductionBom;
import com.yserp.project.erp.order.productbom.domain.ProductionBomItem;
import com.yserp.project.erp.order.productbom.service.IProductionBomItemService;
import com.yserp.project.erp.order.productbom.service.IProductionBomService;
import com.yserp.project.erp.order.productorder.domain.ProductionOrder;
import com.yserp.project.erp.order.productorder.domain.ProductionOrderDto;
import com.yserp.project.erp.order.productorder.domain.ProductionOrderItem;
import com.yserp.project.erp.order.productorder.domain.ProductionOrderVo;
import com.yserp.project.erp.order.productorder.mapper.ProductionOrderMapper;
import com.yserp.project.erp.order.productorder.service.IProductionOrderItemService;
import com.yserp.project.erp.order.productorder.service.IProductionOrderService;
import com.yserp.project.erp.order.saleorder.domain.ErpSaleOrder;
import com.yserp.project.erp.order.saleorder.domain.ErpSaleOrderItem;
import com.yserp.project.erp.order.saleorder.service.IErpSaleOrderItemService;
import com.yserp.project.erp.order.saleorder.service.IErpSaleOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 生产批次Service业务层处理
 *
 * @author yserp
 * @date 2022-07-19
 */
@Service
public class ProductionOrderServiceImpl extends ServiceImpl<ProductionOrderMapper, ProductionOrder> implements IProductionOrderService  {

    @Resource
    private ProductionOrderMapper productionOrderMapper;
    @Autowired
    private IProductionOrderItemService productionOrderItemService;
    @Autowired
    private IErpSaleOrderService saleOrderService;
    @Autowired
    private IErpSaleOrderItemService saleOrderItemService;
    @Autowired
    private IProductionBomService productionBomService;
    @Autowired
    private IProductionBomItemService productionBomItemService;

    /**
     * 查询生产批次
     *
     * @param id 生产批次主键
     * @return 生产批次
     */
    @Override
    public ProductionOrderVo selectProductionOrderById(Long id) {
        ProductionOrderVo vo = new ProductionOrderVo();
        vo.setProductionOrder(productionOrderMapper.selectById(id));
        vo.setItems(productionOrderItemService.selectProductionOrderItemListByMainId(id));
        return vo;
    }

    /**
     * 查询生产批次列表
     *
     * @param productionOrder 生产批次
     * @return 生产批次
     */
    @Override
    public List<ProductionOrder> selectProductionOrderList(ProductionOrder productionOrder) {
        QueryWrapper<ProductionOrder> queryWrapper = new QueryWrapper<>();
        MybatisPlusUtil.notNullField(productionOrder,queryWrapper);
        return productionOrderMapper.selectList(queryWrapper);
    }

    /**
     * 新增生产批次
     *
     * @param productionOrderDto 生产批次
     * @return 结果
     */
    @Override
    @Transactional
    public int insertProductionOrder(ProductionOrderDto productionOrderDto) {

        List<ProductionOrderItem> items = productionOrderDto.getItems();
        if (CollectionUtils.isEmpty(items)) {
            throw new BusinessException("子表不能为空");
        }
        //验证单号是否存在
        String orderNo = productionOrderDto.getOrderNo();
        if(StringUtils.isBlank(orderNo)){
            throw new BusinessException("单号不存在");
        }
        Integer count = productionOrderMapper.selectCount(new QueryWrapper<ProductionOrder>().eq("order_no", orderNo));
        if(count>0){
            //处理单号，并重新插入缓存
            Integer number = productionOrderMapper.selectCount(new QueryWrapper<ProductionOrder>().like("order_no", orderNo.substring(0,orderNo.length()-3)));
            OrderEnums.putCacheOrderNo(orderNo,number);
            throw new BusinessException("单号已存在，请重新下单");
        }else{
            OrderEnums.putCacheOrderNo(orderNo);
        }
        //插入主表
        ProductionOrder productionOrder = new ProductionOrder();
        BeanUtils.copyBeanProp(productionOrder, productionOrderDto);
        int i = productionOrderMapper.insert(productionOrder);
        //批量插入子表
        items.stream().forEach(item-> item.setMainId(productionOrder.getId()));
        productionOrderItemService.saveBatch(items);
        return i;
    }

    /**
     * 修改生产批次
     *
     * @param productionOrderDto 生产批次
     * @return 结果
     */
    @Override
    @Transactional
    public int updateProductionOrder(ProductionOrderDto productionOrderDto) {
        List<ProductionOrderItem> items = productionOrderDto.getItems();
        if(CollectionUtils.isEmpty(items)){
            throw new BusinessException("子表不能为空");
        }
        //修改主表
        ProductionOrder productionOrder = new ProductionOrder();
        BeanUtils.copyBeanProp(productionOrder, productionOrderDto);
        int i = productionOrderMapper.updateById(productionOrder);
        //子表
        Long mainId = productionOrder.getId();
        //获取子表
        List<ProductionOrderItem> productionOrderItems = productionOrderItemService.selectProductionOrderItemListByMainId(mainId);
        if(!CollectionUtils.isEmpty(productionOrderItems)) {
            List<Long> oldIds = productionOrderItems.stream().map(ProductionOrderItem::getId).collect(Collectors.toList());
            List<Long> newIds = items.stream().map(ProductionOrderItem::getId).collect(Collectors.toList());
            oldIds.removeAll(newIds);
            if (!CollectionUtils.isEmpty(oldIds)) {
                productionOrderItemService.removeByIds(oldIds);
            }
        }
        for (ProductionOrderItem item : items) {
            item.setMainId(mainId);
            productionOrderItemService.saveOrUpdate(item);
        }
        return i;
    }

    @Override
    @Transactional
    public int updateProductionOrderStatus(ProductionOrder productionOrder) {
        //更新生产单状态
        Long id = productionOrder.getId();
        String status = productionOrder.getProductStatus();
        if(null == id || StringUtils.isEmpty(status)){
            throw new BusinessException("获取入参为空");
        }
        //查询主数据
        ProductionOrder production = productionOrderMapper.selectById(id);
        Long saleOrderId = production.getSaleOrderId();
        if(null != saleOrderId){
            //更新生产状态
            ErpSaleOrder erpSaleOrder = new ErpSaleOrder();
            erpSaleOrder.setId(saleOrderId);
            erpSaleOrder.setProduceStatus(status);
            saleOrderService.updateErpSaleOrderStatus(erpSaleOrder);
        }
        //更新状态
        ProductionOrder update = new ProductionOrder();
        update.setId(id);
        update.setProductStatus(status);
        return productionOrderMapper.updateById(update);
    }

    /**
     * 批量删除生产批次
     *
     * @param ids 需要删除的生产批次主键
     * @return 结果
     */
    @Override
    public int deleteProductionOrderByIds(String ids) {
        int result = 0;
        Long[] mainIds = Convert.toLongArray(ids);
        for (Long id : mainIds ) {
            result =deleteProductionOrderById(id);
            if(result <= 0){
                break;
            }
        }
        return result;
    }

    /**
     * 删除生产批次信息
     *
     * @param id 生产批次主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteProductionOrderById(Long id) {
        int result = 0;
        //更新主表
        int i=productionOrderMapper.deleteById(id);
        //更新子表
        //查询子表信息
        List<ProductionOrderItem> items = productionOrderItemService.selectProductionOrderItemListByMainId(id);
        if(!CollectionUtils.isEmpty(items)) {
            List<Long> itemIds = items.stream().map(ProductionOrderItem::getId).collect(Collectors.toList());
            boolean b = productionOrderItemService.removeByIds(itemIds);
            if (i > 0 && b) {
                result = 1;
            }
        }
        return result;
    }

    @Override
    public int auditProductionOrderByIds(String ids) {
        Long[] mainIds = Convert.toLongArray(ids);
        ProductionOrder order=null;
        List<ProductionOrder> orders =new ArrayList<>();
        for (Long id : mainIds ) {
            order = productionOrderMapper.selectById(id);
            //如果已审核，无须再次审核
            if(CheckStatusEnums.OK_CHECK.getCode().equals(order.getOrderStatus())){
                continue;
            }
            order.setOrderStatus(CheckStatusEnums.OK_CHECK.getCode());
            orders.add(order);
        }
        if(orders.size()>0) {
           this.updateBatchById(orders);
        }
        return 1;
    }

    @Override
    public ProductionOrderVo saleTransProduct(Long id) {
        ProductionOrderVo productionOrderVo = new ProductionOrderVo();
        if(null == id){
            return productionOrderVo;
        }
        //1.查询销售的产品信息
        ErpSaleOrderItem saleOrderItem = saleOrderItemService.getById(id);
        if(null == saleOrderItem){
            return productionOrderVo;
        }
        ErpSaleOrder saleOrder = saleOrderService.getById(saleOrderItem.getSaleOrderId());
        if(null == saleOrder){
            return productionOrderVo;
        }
        //2.查询bom信息
        List<ProductionBomItem> mapList = productionBomItemService.selectProductionBomItemListByProductId(saleOrderItem.getGoodsId());
        if(CollectionUtils.isEmpty(mapList)){
            return productionOrderVo;
        }
        ProductionBom productionBom = productionBomService.getById(mapList.get(0).getMainId());
        if(null == productionBom){
            return productionOrderVo;
        }
        //3.组装数据
        //主表
        ProductionOrder productionOrder = new ProductionOrder();
        productionOrder.setSaleOrderId(saleOrder.getId());
        productionOrder.setSaleOrderNo(saleOrder.getOrderCode());
        productionOrder.setCustomerId(saleOrder.getCustomerId());
        productionOrder.setCustomerName(saleOrder.getCustomerName());
        productionOrder.setGoodsId(saleOrderItem.getGoodsId());
        productionOrder.setGoodsCode(saleOrderItem.getGoodsCode());
        productionOrder.setGoodsName(saleOrderItem.getGoodsName());
        productionOrder.setGoodsUnit(saleOrderItem.getGoodsUnit());
        productionOrder.setGoodsUnitDesc(saleOrderItem.getGoodsUnitDesc());
        productionOrder.setGoodsNum(productionBom.getProductMinNum());
        //子表
        List<ProductionOrderItem> items = new ArrayList<>();
        if(!CollectionUtils.isEmpty(mapList)){
            ProductionOrderItem productionOrderItem =null;
            for (ProductionBomItem item : mapList) {
                productionOrderItem = new ProductionOrderItem();
                productionOrderItem.setGoodsId(item.getGoodsId());
                productionOrderItem.setGoodsCode(item.getGoodsCode());
                productionOrderItem.setGoodsName(item.getGoodsName());
                productionOrderItem.setGoodsUnit(item.getGoodsUnit());
                productionOrderItem.setGoodsUnitDesc(item.getGoodsUnitDesc());
                productionOrderItem.setPlanNumber(item.getPlanNumber());
                productionOrderItem.setRemark("");
                items.add(productionOrderItem);
            }
        }
        productionOrderVo.setProductionOrder(productionOrder);
        productionOrderVo.setItems(items);
        return productionOrderVo;
    }
}
